package com.bsj.pay.controller.merchant;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.common.Result;
import com.bsj.pay.model.MerchantBean;
import com.bsj.pay.service.MerchantService;
import com.bsj.pay.util.security.MD5;

@Controller("merchantUserController")
@RequestMapping("/merchant/user")
public class UserController {
	
	@Autowired
	private MerchantService merchantService;
	
	@ResponseBody
	@RequestMapping("/login.html")
    public Result login(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,String userName,String password) {
		Result result=new Result();
		if(StringUtils.isEmpty(userName))
		{
			result.setCode(1);
			result.setMsg("请输入账号");
			return result;
		}
		if(StringUtils.isEmpty(password))
		{
			result.setCode(1);
			result.setMsg("请输入密码");
			return result;
		}
		try {
			MerchantBean user=new MerchantBean();
			user.setId(Long.parseLong(userName));
			List<MerchantBean> users=merchantService.queryList(user);
			if(users==null||users.size()==0)
			{
				result.setCode(1);
				result.setMsg("用户不存在");
				return result;
			}
			MerchantBean loginUser=users.get(0);
			if(!loginUser.getPassword().equals(MD5.getMD5(password)))
			{
				result.setCode(1);
				result.setMsg("密码错误");
				return result;
			}
			if(loginUser.getStatus()==0)
			{
				result.setCode(1);
				result.setMsg("账号被禁用");
				return result;
			}
			result.setCode(0);
			result.setMsg("登录成功");
			request.getSession().setAttribute("muser", loginUser);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}
    }
	
	
	@ResponseBody
	@RequestMapping("/updatePassword.html")
	public Result updatePassword(HttpServletRequest request,HttpServletResponse response,String password,String password1){
		Result result=new Result();
		if(StringUtils.isEmpty(password))
		{
			result.setCode(1);
			result.setMsg("请输入原始密码");
			return result;
		}
		if(StringUtils.isEmpty(password1))
		{
			result.setCode(1);
			result.setMsg("请输入新密码");
			return result;
		}
		if(!password1.equals(password))
		{
			result.setCode(1);
			result.setMsg("两次输入密码不一致");
			return result;
		}
		MerchantBean muser=(MerchantBean) request.getSession().getAttribute("muser");
		MerchantBean merchant=new MerchantBean();
		merchant.setId(muser.getId());
		merchant.setPassword(MD5.getMD5(password));
		merchantService.update(merchant);
		result.setCode(0);
		result.setMsg("修改成功");
		return result;
	}
}
